class FieldData{
    constructor (fieldName, fieldComment, typeClassName, typeClassShortName, isIdentity, isAutoIncrement, isNullable, hasForeignKey) {
        this.fieldName = fieldName;
        this.fieldComment = fieldComment;
        this.typeClassName = typeClassName;
        this.typeClassShortName = typeClassShortName;
        this.isIdentity = isIdentity;
        this.isAutoIncrement = isAutoIncrement;
        this.isNullable = isNullable;
        this.hasForeignKey = hasForeignKey;
    }
}
class EntityData{
    constructor(entityTableName, entityFullName, entityComment, isBasicBean, isTreeStructure, fields) {
        this.entityTableName = entityTableName;
        this.entityFullName = entityFullName;
        this.entityComment = entityComment;
        this.isBasicBean = isBasicBean;
        this.isTreeStructure = isTreeStructure;
        this.fields = fields;
    }
}
const TABLE_JS = $('#tableJs');
//URL根目录
const BASE_URL = TABLE_JS.attr('requestUrl');
//页面增删改查请求的URL
const REQUEST_URL = BASE_URL+"/UniCrudServlet";
//实体数据 JSON
const ENTITY_DATA_JSON = TABLE_JS.attr('entityData');
const ENTITY_DATA = Object.assign(new EntityData,JSON.parse(ENTITY_DATA_JSON));
//实体类名，全名
const ENTITY_CLASS_NAME = ENTITY_DATA.entityFullName;
const ENTITY_CONDITION = TABLE_JS.attr('condition');
const ENTITY_CLASS_NAME_JSON = {'entityClassName': ENTITY_CLASS_NAME,'condition':ENTITY_CONDITION};
//实体中文名称
const ENTITY_COMMENT= ENTITY_DATA.entityComment;

//ID字段名
//弹窗模式，有POST添加，PUT修改两个模式
let modalMode = "POST";
//实体类名称
//全部数据
let tableAllData;




$.when(loadTableData()).done(function (a){
    renderTableData();
    renderTableDataMoney();
    furtherLoadData();
    loadModalDropdown();
    $('#loadingSpinner').hide();
})
function loadModalDropdown() {
    let dropdowns = $("select[needLoadDropdownMenu='true']");
    dropdowns.each(function () {
        let select = $(this);
        let tableName = select.attr('typeClassShortName');
        let isGenId = select.attr('isGeneratedId');
        $.getJSON(BASE_URL+"/FkValueListServlet?isGenId="+isGenId+"&table="+tableName, {}, (jsonArray)=>{
            let newOption;
            if(tableName==="ItemInfo")
                isGenId="false";

            if(isGenId==="true"){
                $.each(jsonArray,(index , ids)=>{
                    newOption = new Option(ids,ids,false,false);
                    select.append(newOption).trigger('change');
                });
            }else{
                $.each(jsonArray,(index,object)=>{
                    let id = object.id;
                    let name = object.name;
                    newOption = new Option(name,id,false,false);
                    select.append(newOption).trigger('change');
                });
            }


        });

    });
    $('.post-put-input').each(function (){
       let inputElement = $(this);
    });
}
//所有和钱有关的列都加上￥ .00
function renderTableDataMoney() {
    $("td[isMoney='true']").each(function (){
        let td = $(this);
        let value = td.text();
        let format = Intl.NumberFormat("en-US", {
            style: "currency",
            currency: "CNY",
            useGrouping: true,
            minimumFractionDigits: 2
        }).format(value); // $148,000
        td.text(format.replace('CN',''));
    });
}
let totalFkValueAmount;
//载入外键内容
function furtherLoadData() {
    let $td = $("td[needfurtherload='true']");
    totalFkValueAmount = $td.length;
    $('#resource_total').text(totalFkValueAmount);
    let resLoaded = 0;
    $td.each(function(){
        let td = $(this);
        let value = td.text();
        let i = td.index();
        let tableHead = td.closest('table').find('th').eq(i);
        let tableName = $(tableHead).attr('typeClassShortName');
        $.ajax({
            url: BASE_URL+"/IdNameQueryServlet",
            type : 'GET',
            data : {'id':value,'table':tableName},
            contentType : 'application/json',
            dataType: 'text',
            async: true,
            success: function (resp){
                td.text(resp);
                resLoaded++;
                $('#resource_loaded').text(resLoaded);
                let percent = (resLoaded / totalFkValueAmount)*100;
                $('#progressBar').css('width',percent+'%').attr('aria-valuenow', percent);
            }
        });
    });
}
//读取json，写入全局变量
function loadTableData(){
    return $.getJSON(REQUEST_URL, ENTITY_CLASS_NAME_JSON, (jsonArray)=>{
            tableAllData=jsonArray;
        });
}
//读取json全局变量，渲染表格
function renderTableData(){
    return $.each(tableAllData,(index,object)=>{
        let rowHtml = `<tr rowIndex="${index}" class="tableRow_clickable">`;

        $.each(object,(fieldName,value)=>{
            if(value instanceof Object){
                //如果读取到了一个对象（外键），先把id写上
                rowHtml+=`<td needFurtherLoad="true" rowIndex="${index}" fieldName="${fieldName}" value="${value.id}" >${value.id}</td>`;
            }else{
                if($(`th[fieldName='${fieldName}'][isMoney='true']`).length)
                    rowHtml+=`<td rowIndex="${index}" fieldName="${fieldName}" isMoney="true" >${value}</td>`;
                else
                    rowHtml+=`<td rowIndex="${index}" fieldName="${fieldName}"  >${value}</td>`;
            }

        })

        rowHtml += "</tr>";

        $('#tableBody').append(rowHtml);
    });


}
//添加/修改数据
function sendModalData(){
    let $modalForm = $('#modalForm');
    let modalFormData2Send = $modalForm.serialize();
    console.log(modalFormData2Send);
    $.ajax({
        url: REQUEST_URL,
        type: modalMode,
        data: modalFormData2Send,
        contentType: 'application/json',
        dataType: 'text',
        success : ()=>{
            alert('提交成功！');
            location.reload();
        },
        error : ()=>{
            alert('失败');
        }
    });
}

 function del() {
    let selectedRow = document.getElementsByClassName("highlight")[0];
    console.log(selectedRow);
    if(selectedRow===undefined){
        alert("请选择一行数据！");
        return;
    }
    let tableDataCells = selectedRow.getElementsByTagName("td");
    let idCellValue;
    for (let td of tableDataCells) {
        if($(td).attr('fieldName')==='id')
            idCellValue=td.textContent;
    }
    let dataz = {
        'entityClassName': ENTITY_CLASS_NAME,
        'idValue': idCellValue
    };
    $.ajax({
        url: REQUEST_URL,
        type : 'DELETE',
        data : dataz,
        contentType : 'application/json',
        dataType: 'text',
        success : ()=>{
            alert("成功删除！");
            clearTableData();
            loadTableData();
        },
        error : ()=>{
            alert('失败');
        }
    });

}
function edit(){
    modalMode = 'PUT';
    $('#modalTitle').text('修改'+ENTITY_COMMENT);
    if($(".highlight").length===0){
        alert("请选择一行数据！");
        return;
    }
    let tableDataCells = $('.highlight > td');
    //遍历每一个表格数据td
    tableDataCells.each(function (index) {
        let td = $(this);
        let fieldName = td.attr('fieldName');
        let tdText = td.text().replace('￥','').replace("¥","").replace(',','')
            if(td.attr('needFurtherLoad')==="true"){
                let fkValue = td.attr('value');
                let $1 = $(`#select2_${fieldName}`);
                $1.val(fkValue);
                $1.trigger('change');
            }else{
                $(`input[name='${fieldName}']`).val(tdText);
            }
        if(index===0){
            $('#generatedIdInput').val(tdText);

        }
    }) ;
}
function add(){
    modalMode = 'POST';
    $('#modalTitle').text('添加'+ENTITY_COMMENT);
    $("input.form-control.post-put-input:text:not([readonly])").val('');
    $('#generatedIdInput').val(TABLE_JS.attr('goid'));
}
